package cn.tedu._06article.controller;


import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import cn.tedu._06article.mapper.UserMapper;
import cn.tedu._06article.pojo.dto.UserArticleParam;
import cn.tedu._06article.pojo.dto.UserLoginParam;
import cn.tedu._06article.pojo.entity.Article;
import cn.tedu._06article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Validated
@Slf4j
@Tag(name = "01-用户模块")
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperationSupport(order=10)
    @Operation(summary = "登录功能")
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam,HttpSession session){
        log.debug("登录业务,参数" + userLoginParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

    @PostMapping("/article")
    @ApiOperationSupport(order = 20)
    @Operation(summary = "发布文章")
    public JsonResult article(@RequestBody UserArticleParam userArticleParam,HttpSession session){
        log.debug("发布文章业务参数" + userArticleParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUserId(userVO.getId());
        int i = userMapper.insertArticle(article);
        if(i>0){
            return JsonResult.ok(article);
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }



}
